package com.learnyou.server.xingzuo.common.util;

import cn.hutool.http.HttpUtil;
import net.coobird.thumbnailator.Thumbnails;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @author heweifeng
 * @Description:
 * @date 2022/2/16 16:14
 */
public class ImageUtils {

    /**
     * @description 图片压缩
     * @author heweifeng
     * @updateTime 2022/2/11 17:26
     */
    public static byte[] resizeImage(byte[] image){
        ByteArrayOutputStream resizeOutputStream = new ByteArrayOutputStream();
        //判断大小,如果小于100k,不压缩,如果大于等于100k,压缩
        if(image.length <=  50*1024){
            return image;
        }
        try {
            Thumbnails.of(new ByteArrayInputStream(image))
                    .scale(0.8)
                    .imageType(BufferedImage.TYPE_INT_RGB)
                    .toOutputStream(resizeOutputStream);
            return resizeImage(resizeOutputStream.toByteArray());
        } catch (Exception e) {
            return image;
        }
    }
    /**
     * @description 从图片url下载图片
     * @author heweifeng
     * @updateTime 2022/2/11 17:22
     */
    public static byte[] readImage(String imageUrl){
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        HttpUtil.download(imageUrl, outputStream, true);
        return outputStream.toByteArray();
    }
}
